package com.focus.xyz.union.action;

import com.focus.xyz.core.common.keyword.Action;
import com.focus.xyz.core.common.webdriver.DriverFactory;
import com.focus.xyz.core.utils.Constants;
import com.focus.xyz.core.utils.CookieUtils;
import com.focus.xyz.core.utils.ProcessUtil;
import com.focus.xyz.core.utils.prop.ConfigPropInfo;
import com.focus.xyz.main.pages.XyzHomePage;
import com.focus.xyz.union.data.InsDataBean;
import com.focus.xyz.union.data.InsDataService;
import com.focus.xyz.union.data.SubAcctBean;
import com.focus.xyz.union.pages.backend.BackMenuList;
import com.focus.xyz.union.pages.backend.MemInfoPage;
import com.focus.xyz.union.pages.backend.ProdScope;
import com.focus.xyz.union.pages.backend.XyzMainPage;
import com.focus.xyz.union.pages.backend.tables.MemTable;
import com.focus.xyz.union.pages.frontend.*;
import com.focus.xyz.union.pages.frontend.forms.AppInputForm;
import com.focus.xyz.union.pages.frontend.forms.ApplicantForm;
import com.focus.xyz.union.pages.frontend.forms.InsPlanForm;
import com.focus.xyz.union.pages.frontend.forms.InsuredForm;
import com.focus.xyz.union.pages.frontend.tables.ProxyProdTable;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;

import java.io.File;
import java.util.List;

/**
 * Created by chenmeng on 2016/4/27.
 */
public class KeyWordAction extends Action {
    private static transient Logger logger = LoggerFactory.getLogger(KeyWordAction.class);
    private WebDriver driver;
    private MemTable memTable;

    //普通方式，供@Test使用
    public KeyWordAction(WebDriver driver) {
        super(driver);
        this.driver = driver;
    }

    public void OpenBrowser(String nodeUrl,String browser) throws Exception{
        driver = DriverFactory.getDriver(nodeUrl).getBrowser(browser);
    }

    public void CloseBrowser(){
        try {
            driver.quit();
        }catch (Exception e){
            logger.error(e.getMessage());
        }finally {
            /*if(ProcessUtil.findProcess("iexplore.exe")){
                ProcessUtil.killProcess("iexplore.exe");
            }*/
        }
    }

    /*
    * 渠道后台登录
    * */
    public void LoginBack(String username,String pass) throws Exception{
        XyzMainPage xyzMainPage = new XyzMainPage(driver,this);
        xyzMainPage.openPage();
        CookieUtils.addCookie(driver, ConfigPropInfo.TEST_DATA_DIR + "cookies/" + ConfigPropInfo.UNION_BACK_LOGIN_COOKIE_FILE);
        xyzMainPage.openPage();
        if(!xyzMainPage.isLogined()){
            xyzMainPage.login(username,pass,"");
            CookieUtils.saveCookie(driver, ConfigPropInfo.TEST_DATA_DIR + "cookies/" + ConfigPropInfo.UNION_BACK_LOGIN_COOKIE_FILE,".xyz.cn");
            waitForPageLoad();
        };
        xyzMainPage.linkUnion();
        pause(1000l);

    }

    /*
    * 渠道前台登录
    * */
    public void LoginFront(String userName,String pass) throws Exception{
        MainPage mainPage = new MainPage(driver,this);
        mainPage.openPage();
        CookieUtils.addCookie(driver, ConfigPropInfo.TEST_DATA_DIR + "cookies/" + ConfigPropInfo.UNION_FRONT_LOGIN_COOKIE_FILE);
        mainPage.openPage();
        if (!mainPage.isLogined()) {
            mainPage.login(userName, pass);
            CookieUtils.saveCookie(driver, ConfigPropInfo.TEST_DATA_DIR + "cookies/" + ConfigPropInfo.UNION_FRONT_LOGIN_COOKIE_FILE, ConfigPropInfo.UNION_DOMAIN);
            waitForPageLoad();
        }
    }

    public void XyzLoginFront(String userName,String pass) throws Exception{
        com.focus.xyz.main.pages.XyzMainPage xx = new com.focus.xyz.main.pages.XyzMainPage(driver,this);
        xx.openPage();
        CookieUtils.addCookie(driver, ConfigPropInfo.TEST_DATA_DIR + "cookies/" + ConfigPropInfo.XYZ_FRONT_LOGIN_COOKIE_FILE);
        xx.openPage();
        if (!xx.isLogined()) {
            xx.clickLoginLink();
            xx.login(userName, pass);
            CookieUtils.saveCookie(driver, ConfigPropInfo.TEST_DATA_DIR + "cookies/" + ConfigPropInfo.XYZ_FRONT_LOGIN_COOKIE_FILE, ConfigPropInfo.XYZ_DOMAIN);
            waitForPageLoad();
        }
    }

    public void XyzLogoutFront() throws Exception{
        XyzHomePage xp = new XyzHomePage(driver,this);
        xp.logout();
        pause(2000l);
    }


    /*
    *代理人登录后在【我要填单】中打开投保页面
    * */
    public void OpenToubaoPage(String prodName) throws Exception{
        FrontMenuList menuList = new FrontMenuList(driver,this);
        menuList.openMenu(Constants.U_F_TB_MENU);
        ProxyProdTable ptable = new ProxyProdTable(driver,this);
        ptable.linkDetail(prodName);
    }

    /*
    * 投保公共操作
    * */
    public void CommonToubao(InsDataBean bean) throws Exception{
        /*打开产品详情页面*/
        ProdDetailPage pd = new ProdDetailPage(driver,this);
        /*等待页面加载完成*/
        waitForPageLoad();
        /*立即投保*/
        pause(2000l);//定位“立即投保”按钮存在问题
//        pd.clickTbBtn();
        pd.clickTbBtnChrome();
        /*打开保单填写页面*/
        AppInputForm aform = new AppInputForm(driver,this);
        /*等待页面加载完成*/
        waitForPageLoad();
        pause(5000l);
        /*填写保险计划*/
        InsPlanForm ipform = new InsPlanForm(driver,this);
        ipform.fillInsPlan(bean.getPlanId());
        aform.clickInputInsured();
        /*添加被保险人*/
        InsuredForm iform = new InsuredForm(driver,this);
        iform.addInsured(bean.getInsuredId());
        /*添加投保人*/
        ApplicantForm af = new ApplicantForm(driver,this);
        af.fillApplicant1(InsDataService.getApplicantById(bean.getApplicantId()));
        /*投保*/
        aform.toubao(bean.getType());
        waitForPageLoad();//创建订单等待时间
    }

    /*团体险种投保操作*/
    public void TuantiToubao(InsDataBean bean) throws Exception{
        ProdDetailPage pd = new ProdDetailPage(driver,this);
        /*等待页面加载完成*/
        waitForPageLoad();
        pause(2000l);
        /*立即投保*/
        pd.clickTbBtnChrome();
        AppInputForm aform = new AppInputForm(driver,this);
        /*等待页面加载完成*/
        waitForPageLoad();
        /*填写保险计划*/
        aform.addInsPlan(bean.getPlanId());
        pause(1000l);
        /*上传被保人*/
        aform.uploadInsuredInfo(bean.getInsuredId());
        pause(2000l);
        /*添加公司信息*/
        aform.addCompanyInfo();
        /*投保*/
        aform.submitOrder();
        waitForPageLoad();//创建订单等待时间
    }

    /*
    * 支付，使用银联支付
    * */
    public void CommonUnionpay() throws Exception{
        /*订单创建完成后支付*/
        UnionPayPage up = new UnionPayPage(driver,this);
        waitForPageLoad();
        pause(2000l);
        up.clickUnionPayLink();
        waitForPageLoad();
        up.unionpay();
        assertStringTrue("支付成功");//验证订单支付是否成功
        up.linkOrderInfo();
        OrderInfoPage op = new OrderInfoPage(driver,this);
        waitForPageLoad();
        String status = op.getOrderStatus();
        if(StringUtils.isBlank(status)||!status.contains("已支付")){
            Assert.fail("订单状态异常");
        }
    }

    /*
    * 使用充值账户支付
    * */
    public void AcctPay(String expectedPrice,String payPass) throws Exception{
        UnionPayPage up = new UnionPayPage(driver,this);
        if(StringUtils.isNotBlank(expectedPrice)&&expectedPrice.indexOf(".")<0){
            expectedPrice = expectedPrice + ".00";
        }
        pause(1000l);
        String aTotalPrice = up.getTotalPrice();
        if(!aTotalPrice.equals(expectedPrice)){
            fail("保费合计金额显示与预期金额不符");
        }
        String actualPrice = up.getPayPrice();
        actualPrice = actualPrice.substring(1);
        if(StringUtils.isNotBlank(actualPrice.trim())){
            if(StringUtils.equals(expectedPrice,actualPrice.trim())){
                up.acctPay(payPass);
                waitForPageLoad();
                assertStringTrue("支付成功");
            }else{
                fail("实际支付金额与预期支付金额不符。");
            }
        }else{
            fail("支付金额显示为空。");
        }
    }

    /*
    * 修改结算方式
    * */
    public void ChangeSettleType(String memName,String type) throws Exception{
        BackMenuList menuList = new BackMenuList(driver,this);
        menuList.openExpandMenu("渠道会员管理","查询渠道会员");
        MemTable memTable = new MemTable(driver,this);
        memTable.search(memName);
        pause(1000l);
        memTable.linkText(memName);
        pause(1000l);
        MemInfoPage mip = new MemInfoPage(driver,this);
        mip.modifySettleType(type);
        pause(2000l);

    }

    /*
    * 设置产品范围与投放平台
    * */
    public void SetProdScopeAndPlat(List<String> prodList, String plat) throws Exception{
        ProdScope prodScope = new ProdScope(driver,this);
        for(String ss:prodList){
            //设置产品范围
            prodScope.linkSetProdScope();
            prodScope.setProdScope(ss);
            pause(1000l);
        }
        //设置投放平台
        prodScope.linkSetPlat();
        pause(2000l);
        prodScope.setProdPlat(plat);
        pause(1000l);
    }

    /*
    * 清除渠道前台系统的cookie
    * */
    public static void DelUnionFrontCookie() throws Exception{
        String path = ConfigPropInfo.TEST_DATA_DIR + "cookies/" + ConfigPropInfo.UNION_FRONT_LOGIN_COOKIE_FILE;
        File file = new File(path);
        if(file.exists()){
            FileUtils.forceDelete(file);
            Thread.sleep(2000l);
        }
    }


    /*
    * 渠道前台系统登录
    * */
    public void LogoutFront() throws Exception{
        MainPage mainPage = new MainPage(driver,this);
        mainPage.logout();
    }

    /*
    * 新增子账号
    * */
    public void AddSubAcct(SubAcctBean bean, String pUserName, String prodName) throws Exception{
        FrontMenuList menuList = new FrontMenuList(driver,this);
        menuList.openMenu(Constants.U_F_SUB_MENU);
        SubAcctPage sa = new SubAcctPage(driver,this);
        sa.clickAddBtn();
        sa.fillSubInfo(bean,prodName);
        /*验证子账号*/
        String sta =sa.getSubStatus(pUserName + "_" +bean.getLoginName());
        if(!"使用中".equals(sta)){
            fail("新建子账号异常,账号状态："+sta);
        }
    }

    public void SwitchWindow(String url) throws Exception{
        switchToWindowByUrl(url,true);
    }

    public void OpenBackMenu(String pName,String name) throws Exception{
        BackMenuList menuList = new BackMenuList(driver,this);
        menuList.openExpandMenu(pName,name);
    }

    public void SearchMember(String name) throws Exception{
        memTable = new MemTable(driver,this);
        memTable.search(name);
    }

    public void LinkText(String key,String linkText) throws Exception{
        memTable.openLink(key,linkText);
    }

    public void Wait(String time) throws Exception{
        long t = Long.parseLong(time);
        pause(t);
    }
}
